import pygame
from time import sleep
import random
from pygame.sprite import collide_rect

# 设置通用属性
BG_COLOR = pygame.Color(0, 0, 0)
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
TEXT_COLOR = pygame.Color(255, 0, 0)


class Tank:
    """
    坦克类
    """

    def __init__(self) -> None:
        self.live = True
        self.old_left = 0
        self.old_top = 0

    def display_tank(self) -> None:
        """
        显示坦克
        """
        # 获取最新坦克的动态
        self.image = self.images.get(self.direction)
        MainGame.window.blit(self.image, self.rect)

    def move(self) -> None:
        """
        坦克的移动
        """
        self.old_left = self.rect.left
        self.old_top = self.rect.top
        if self.direction == "L":
            # 判断是否在边界
            if self.rect.left > 0:
                self.rect.left = self.rect.left - self.speed
        elif self.direction == "R":
            if self.rect.left + self.rect.width < SCREEN_WIDTH:
                self.rect.left = self.rect.left + self.speed
        elif self.direction == "U":
            if self.rect.top > 0:
                self.rect.top = self.rect.top - self.speed
        elif self.direction == "D":
            if self.rect.top + self.rect.height < SCREEN_HEIGHT:
                self.rect.top = self.rect.top + self.speed

    def shot(self) -> None:
        """
        坦克的射击
        """
        pass

    def tank_hit_wall(self):
        """
        坦克与墙壁碰撞
        """
        for wall in MainGame.wall_list:
            # 判断坦克是否与墙壁碰撞
            if pygame.sprite.collide_rect(self, wall):
                self.rect.left = self.old_left
                self.rect.top = self.old_top

    def tank_collide_tank(self, tank):
        """
        坦克与坦克碰撞
        """
        if self and tank and self.live and tank.live:
            if pygame.sprite.collide_rect(self, tank):
                self.rect.left = self.old_left
                self.rect.top = self.old_top


class MyTank(Tank):
    """
    我方坦克类
    """

    def __init__(self, left: int, top: int) -> None:
        super(MyTank, self).__init__()
        # 设置我方坦克的图片资源
        self.images = {
            "U": pygame.image.load("./img/p1tankU.gif"),
            "D": pygame.image.load("./img/p1tankD.gif"),
            "L": pygame.image.load("./img/p1tankL.gif"),
            "R": pygame.image.load("./img/p1tankR.gif"),
        }
        # 设置我方坦克的方向
        self.direction = "L"
        # 获取图片信息
        self.image = self.images.get(self.direction)
        # 获取图片矩形
        self.rect = self.image.get_rect()
        # 设置我方坦克的位置
        self.rect.left = left
        self.rect.top = top
        # 设置移动速度
        self.speed = 10
        # 设置移动开关
        self.remove = False


class EnemyTank(Tank):
    """
    敌方坦克类
    """

    def __init__(self, left, top, speed) -> None:
        super(EnemyTank, self).__init__()
        self.images = {
            "U": pygame.image.load("./img/enemy1U.gif"),
            "D": pygame.image.load("./img/enemy1D.gif"),
            "L": pygame.image.load("./img/enemy1L.gif"),
            "R": pygame.image.load("./img/enemy1R.gif"),
        }
        # 设置敌方坦克的方向
        self.direction = self.rand_direction()
        # 获取图片信息
        self.image = self.images.get(self.direction)
        # 获取图片的矩阵
        self.rect = self.image.get_rect()
        # 设置敌方坦克的位置
        self.rect.left = left
        self.rect.top = top
        # 设置移动速度
        self.speed = speed
        # 设置移动步长
        self.step = 20

    def rand_direction(self) -> str:
        """
        生成随机方向
        """
        chice = random.randint(1, 4)
        if chice == 1:
            return "U"
        elif chice == 2:
            return "D"
        elif chice == 3:
            return "L"
        elif chice == 4:
            return "R"

    def rand_move(self):
        """
        随机移动
        """
        # 根据步长切换方向
        if self.step <= 0:
            self.direction = self.rand_direction()
            self.step = 20
        else:
            self.move()
            self.step -= 1

    def shot(self):
        """
        敌方坦克的射击
        """
        num = random.randint(0, 20)
        if num < 1:
            return Bullet(self)


class Bullet:
    """
    子弹类
    """

    def __init__(self, tank) -> None:
        # 加载子弹图片
        self.image = pygame.image.load("./img/enemymissile.gif")
        # 获取子弹方向
        self.direction = tank.direction
        # 获取子弹矩形
        self.rect = self.image.get_rect()
        # 设置子弹位置
        if self.direction == "L":
            self.rect.left = tank.rect.left - self.rect.width
            self.rect.top = tank.rect.top + tank.rect.height / 2 - self.rect.height / 2
        elif self.direction == "R":
            self.rect.left = tank.rect.left + tank.rect.width
            self.rect.top = tank.rect.top + tank.rect.height / 2 - self.rect.height / 2
        elif self.direction == "U":
            self.rect.left = tank.rect.left + tank.rect.width / 2 - self.rect.width / 2
            self.rect.top = tank.rect.top - self.rect.height
        elif self.direction == "D":
            self.rect.left = tank.rect.left + tank.rect.width / 2 - self.rect.width / 2
            self.rect.top = tank.rect.top + tank.rect.height
        self.speed = 10
        # 设置子弹状态
        self.live = True

    def display_bullet(self):
        """
        显示子弹
        """
        MainGame.window.blit(self.image, self.rect)

    def move(self) -> None:
        """
        子弹的移动
        """
        # 根据子弹方向移动
        if self.direction == "L":
            if self.rect.left > 0:
                self.rect.left -= self.speed
            else:
                self.live = False
        elif self.direction == "R":
            if self.rect.left + self.rect.width < SCREEN_WIDTH:
                self.rect.left += self.speed
            else:
                self.live = False
        elif self.direction == "U":
            if self.rect.top > 0:
                self.rect.top -= self.speed
            else:
                self.live = False
        elif self.direction == "D":
            if self.rect.top + self.rect.height < SCREEN_HEIGHT:
                self.rect.top += self.speed
            else:
                self.live = False

    def hit_enemy_tank(self):
        for e_tank in MainGame.enemy_tank_list:
            if collide_rect(self, e_tank):
                # 爆炸效果
                explode = Explode(e_tank)
                MainGame.explot_list.append(explode)
                self.live = False
                e_tank.live = False

    def hit_my_tank(self):
        # 判断我方坦克是否活着
        if MainGame.my_tank and MainGame.my_tank.live:
            # 判断子弹是否与我方坦克碰撞
            if collide_rect(self, MainGame.my_tank):
                # 爆炸效果
                explode = Explode(MainGame.my_tank)
                MainGame.explot_list.append(explode)
                # 子弹状态
                self.live = False
                MainGame.my_tank.live = False

    def hit_wall(self):
        # 判断子弹是否与墙壁碰撞
        for wall in MainGame.wall_list:
            if collide_rect(self, wall):
                self.live = False
                wall.hp -= 1
                if wall.hp <= 0:
                    wall.live = False
                # 攻击墙的特性
                music = Music('./img/hit.wav')
                music.play_music()


class Wall:
    """
    墙壁类
    """

    def __init__(self, left, top) -> None:
        # 加载墙壁图片
        self.image = pygame.image.load("./img/steels.gif")
        # 获取墙壁矩形
        self.rect = self.image.get_rect()
        # 设置墙壁位置
        self.rect.left = left
        self.rect.top = top
        self.hp = 3
        self.live = True

    def display_wall(self) -> None:
        """
        显示墙壁
        """
        MainGame.window.blit(self.image, self.rect)


class Explode:
    """
    爆炸效果类
    """

    def __init__(self, tank: Tank) -> None:
        # 加载爆炸图片
        self.images = [
            pygame.image.load("./img/blast0.gif"),
            pygame.image.load("./img/blast1.gif"),
            pygame.image.load("./img/blast2.gif"),
            pygame.image.load("./img/blast3.gif"),
            pygame.image.load("./img/blast4.gif"),
        ]
        # 获取爆炸位置
        self.rect = tank.rect
        # 设置爆炸效果的索引
        self.step = 0
        # 获取渲染的图像
        self.image = self.images[self.step]
        # 设置爆炸效果的状态
        self.live = True

    def display_explode(self) -> None:
        """
        显示爆炸效果
        """
        if self.step < len(self.images):
            # 获取渲染的图像
            self.image = self.images[self.step]
            # 获取下一帧的图像
            self.step += 1
            # 显示爆炸效果
            MainGame.window.blit(self.image, self.rect)
        else:
            self.step = 0
            self.live = False


class Music:
    """
    音效类
    """
    pygame.mixer.init()
    def __init__(self,filename:str) -> None: 
        # 创建音乐文件
        pygame.mixer.music.load(filename)
        
    def play_music(self) -> None:
        """
        播放音效
        """
        pygame.mixer.music.play()


class MainGame:
    """
    游戏主窗口类
    """

    # 游戏主窗口对象
    window = None
    # 设置我方坦克初始位置
    my_tank = None
    # 存储敌方坦克列表
    enemy_tank_list = []
    # 设置敌方坦克的数量
    enemy_tank_count = 6
    # 存储我方子弹列表
    my_bullet_list = []
    # 存储敌方子弹列表
    enemy_bullet_list = []
    # 存储爆炸效果列表
    explot_list = []
    # 存储墙壁列表
    wall_list = []

    def __init__(self) -> None:
        pass

    def create_enemy_tank(self) -> None:
        """
        创建敌方坦克
        """
        self.enemy_top = 200
        self.enemy_speed = 6
        for i in range(self.enemy_tank_count):
            # 生成坦克的位置
            left = random.randint(0, 600)
            # 创建敌方坦克
            e_tank = EnemyTank(left, self.enemy_top, self.enemy_speed)
            # 敌方坦克添加到列表中
            self.enemy_tank_list.append(e_tank)

    def display_enemy_tank(self) -> None:
        """
        显示敌方坦克
        """
        for e_tank in self.enemy_tank_list:
            if e_tank.live:
                # 显示敌方坦克
                e_tank.display_tank()
                # 敌方坦克移动
                e_tank.rand_move()
                # 判断坦克是否与墙壁碰撞
                e_tank.tank_hit_wall()
                # 判断坦克是否与我方坦克碰撞
                e_tank.tank_collide_tank(MainGame.my_tank)
                # 发射子弹
                e_bullet = e_tank.shot()
                # 子弹添加到列表中
                if e_bullet:
                    MainGame.enemy_bullet_list.append(e_bullet)
            else:
                # 敌方坦克移除
                self.enemy_tank_list.remove(e_tank)
                # 敌方坦克数量减一
                MainGame.enemy_tank_count -= 1

    def display_enemy_bullet(self) -> None:
        """
        显示敌方子弹
        """
        for e_bullet in MainGame.enemy_bullet_list[:]:
            if e_bullet.live:
                e_bullet.display_bullet()
                e_bullet.move()
                # 判断子弹是否击中我方坦克
                e_bullet.hit_my_tank()
                e_bullet.hit_wall()
            else:
                # 子弹移除
                MainGame.enemy_bullet_list.remove(e_bullet)

    def start_game(self) -> None:
        """
        开始游戏
        """
        # 初始化窗口
        pygame.display.init()
        # 创建窗口
        MainGame.window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        # 设置窗口标题
        pygame.display.set_caption("坦克大战1.0")
        # 创建我方坦克
        self.create_my_tank()
        # 创建敌方坦克
        self.create_enemy_tank()
        # 创建墙壁
        self.create_wall()
        # 刷新显示窗口
        while True:
            sleep(0.02)
            MainGame.window.fill(BG_COLOR)
            # 添加提示文字
            # 1.添加文字内容
            # num=6
            text = self.get_text_surface(
                f"敌方剩余坦克数量{len(MainGame.enemy_tank_list)}"
            )
            # 2.将文字加入
            MainGame.window.blit(text, (10, 10))
            # 添加事件
            self.get_event()
            # 判断我方坦克是否死亡
            if MainGame.my_tank and MainGame.my_tank.live:
                # 显示我方坦克
                MainGame.my_tank.display_tank()
            else:
                MainGame.my_tank = None
            # 显示敌方坦克
            self.display_enemy_tank()
            # 判断我方坦克是否死亡
            if MainGame.my_tank and MainGame.my_tank.live:
                # 移动我方坦克
                if MainGame.my_tank.remove:
                    MainGame.my_tank.move()
                    MainGame.my_tank.tank_hit_wall()
                    for e_tank in MainGame.enemy_tank_list:
                        MainGame.my_tank.tank_collide_tank(e_tank)
            # 显示我方子弹
            self.display_my_bullet()
            # 显示敌方子弹
            self.display_enemy_bullet()
            self.display_explot()
            self.display_wall()
            pygame.display.update()

    def create_wall(self) -> None:
        """
        创建墙壁
        """
        top = 200

        for i in range(6):
            # 创建墙壁
            wall = Wall(i * 125, top)
            MainGame.wall_list.append(wall)

    def display_wall(self) -> None:
        """
        显示墙壁
        """
        for wall in MainGame.wall_list:
            if wall.live:
                wall.display_wall()
            else:
                MainGame.wall_list.remove(wall)

    def create_my_tank(self) -> None:
        """
        创建我方坦克
        """
        MainGame.my_tank = MyTank(350, 300)
        # 创建音乐对象
        music = Music('./img/start.wav')
        music.play_music()

    def display_explot(self) -> None:
        """
        显示爆炸效果
        """
        for explode in MainGame.explot_list:
            if explode.live:
                explode.display_explode()
            else:
                MainGame.explot_list.remove(explode)

    def display_my_bullet(self) -> None:
        """
        显示我方子弹
        """
        for m_bullet in self.my_bullet_list:
            if m_bullet.live:
                # 显示子弹
                m_bullet.display_bullet()
                # 子弹移动
                m_bullet.move()
                # 判断子弹是否击中敌方坦克
                m_bullet.hit_enemy_tank()
                m_bullet.hit_wall()
            else:
                # 子弹移除
                self.my_bullet_list.remove(m_bullet)

    def get_text_surface(self, text: str) -> None:
        """
        获取文字的图片
        """
        # 初始化字体模块
        pygame.font.init()
        # 获取可以使用的字体
        # print(pygame.font.get_fonts())
        # 创建字体
        font = pygame.font.SysFont("kaiti", 18)
        # 绘制文字信息
        text_surface = font.render(text, True, TEXT_COLOR)
        # 将绘制的文字信息返回
        return text_surface

    def get_event(self) -> None:
        """
        获取事件
        """
        # 获取所有事件
        event_list = pygame.event.get()
        # 遍历事件
        for event in event_list:
            # 判断事件
            if event.type == pygame.QUIT:
                # 关闭按钮
                self.end_game()
            if event.type == pygame.KEYDOWN:
                if not MainGame.my_tank and event.key == pygame.K_ESCAPE:
                    self.create_my_tank()
                    # self.end_game()

                # 判断坦克是否存在
                if MainGame.my_tank and MainGame.my_tank.live:
                    # 键盘移动
                    if event.key == pygame.K_LEFT:
                        print("坦克向左移动")
                        # 修改方向
                        MainGame.my_tank.direction = "L"
                        # 移动状态
                        MainGame.my_tank.remove = True
                    elif event.key == pygame.K_RIGHT:
                        print("坦克向右移动")
                        # 修改方向
                        MainGame.my_tank.direction = "R"
                        MainGame.my_tank.remove = True
                    elif event.key == pygame.K_UP:
                        print("坦克向上移动")
                        # 修改方向
                        MainGame.my_tank.direction = "U"
                        MainGame.my_tank.remove = True
                    elif event.key == pygame.K_DOWN:
                        print("坦克向下移动")
                        # 修改方向
                        MainGame.my_tank.direction = "D"
                        MainGame.my_tank.remove = True
                    elif event.key == pygame.K_SPACE:
                        if len(MainGame.my_bullet_list) < 6:
                            print("坦克发射子弹")
                            # 创建子弹
                            m_bullet = Bullet(MainGame.my_tank)
                            # 子弹添加到列表中
                            MainGame.my_bullet_list.append(m_bullet)
                            # 音效
                            music =Music('./img/fire.wav')
                            music.play_music()

            if event.type == pygame.KEYUP and event.key in (
                pygame.K_LEFT,
                pygame.K_RIGHT,
                pygame.K_UP,
                pygame.K_DOWN,
            ):
                # 判断坦克是否存在
                if MainGame.my_tank and MainGame.my_tank.live:
                    MainGame.my_tank.remove = False

    def end_game(self) -> None:
        """
        结束游戏
        """
        print("谢谢使用，欢迎再次使用")
        exit()


if __name__ == "__main__":
    # 调用MainGame类中的start_game方法，开始游戏
    MainGame().start_game()
